//
//  selectContactViewController.m
//  TTAddressBook
//
//  Created by 贾政阳 on 12-1-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "selectContactViewController.h"
#import "selectTableCell.h"
#import <QuartzCore/QuartzCore.h>

#define TABLEVIEW_TAG 10
#define POPVIEW_IMAGEVIEW_TAG 11
#define POPVIEW_LABEL_TAG 12
#define UISelectContacts_GreenPopLabel @"contacts_green.png"
@implementation ContactInfo
@synthesize name,checked;

+ (ContactInfo*) initInfo
{
	return [[self alloc] init];
}

- (void) dealloc
{
	[name release];
	[super dealloc];
}
@end

@implementation selectContactViewController
@synthesize keys,filteredListContent;
#pragma mark - View lifecycle
- (id)initWithViewController:(composeMessageViewController*)view{
    if (self = [super init]) {
        composeMessageView = view;
    }
    return self;
}
- (id)init{
    if (self = [super init]) {
        
        if (contactInfoArray == nil) {
            contactInfoArray = [[NSMutableArray alloc] init];
        }
        [contactInfoArray removeAllObjects];
        for (NSInteger idx = 0; idx < 50; idx++)
        {
            ContactInfo* info = [ContactInfo initInfo];
            info.name = [NSString stringWithFormat:@"Name %2d", idx];
            [contactInfoArray addObject:info];
            [info release];
        }
    }
    return self;
}

- (void)dealloc{
    
    [contactInfoArray removeAllObjects];
    [contactInfoArray release];
    contactInfoArray = nil;
    
    [keyArray release];
    
    self.keys = nil;
    
    [filteredListContent removeAllObjects];
    self.filteredListContent = nil;
    
    [searchDC release];
    
    [super dealloc];
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    UIView* selfView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    selfView.backgroundColor = [UIColor whiteColor];
    self.view = selfView;
    [selfView release];
    

    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
	tableView.tag = TABLEVIEW_TAG;
	// set the autoresizing mask so that the table will always fill the view
	tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
	
	// set the cell separator to a single straight line.
	tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	// set the tableview delegate to this object and the datasource to the datasource which has already been set
	tableView.delegate = self;
	tableView.dataSource = self;
	//tableView.sectionIndexMinimumDisplayRowCount=10;
    
	// set the tableview as the controller view
	[self.view addSubview:tableView];
    
    // Create a search bar
	selSearchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	selSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	selSearchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    selSearchBar.delegate = self;
	tableView.tableHeaderView = selSearchBar;

	// Create the search display controller
	searchDC = [[UISearchDisplayController alloc] initWithSearchBar:selSearchBar contentsController:self];
	searchDC.searchResultsDataSource = self;
	searchDC.searchResultsDelegate = self;
    searchDC.delegate = self;
    
    
	[tableView release];

}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.keys = [[composeMessageView.allContactDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    keyArray = [[NSArray alloc] initWithObjects: @"#", @"A", @"B", @"C", @"D", @"E", @"F", @"G",@"H", @"I", @"J", @"K", @"L", @"M", @"N",@"O", @"P", @"Q", @"R", @"S", @"T", @"Y",@"V", @"W", @"X", @"Y", @"Z", nil];
    
    self.navigationItem.title = @"选择成员";
    
    //显示点击索引时出现的字母
    UIImageView* popLabelBackImg = [[UIImageView alloc] initWithFrame:CGRectMake(132, 184, 51, 51)];
    popLabelBackImg.tag = POPVIEW_IMAGEVIEW_TAG;
    popLabelBackImg.image = [UIImage imageNamed:UISelectContacts_GreenPopLabel];
    popLabelBackImg.alpha = 0;
    [self.view addSubview:popLabelBackImg];
    [popLabelBackImg release];
    
	UILabel* label = [[UILabel alloc] initWithFrame: CGRectMake( 132, 184, 51, 51)];
    label.tag = POPVIEW_LABEL_TAG;
	label.textColor = [UIColor whiteColor];
	label.backgroundColor = [UIColor blackColor];
	label.font = [UIFont systemFontOfSize: 40];
	label.textAlignment = UITextAlignmentCenter;
	label.layer.cornerRadius = 8;
	label.alpha = 0;
	[self.view addSubview: label];
    [label release];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark Table view data source

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG]){
        UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        head.backgroundColor = [UIColor colorWithRed:185.0/255 green:188.0/255 blue:194.0/255 alpha:1.0];
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, 60, 20)];
        label1.text = [keys objectAtIndex:section];
        label1.textColor = [UIColor whiteColor];
        label1.backgroundColor = [UIColor clearColor];
        [head addSubview:label1];
        [label1 release];
        return head;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG]){
        return 20;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{	
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG]){
        return keyArray;
    }
    return nil;
}

//选中索引时，中间显示个大字母标签可以淡出
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger charIndex = 0;
    
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG]){
        UIImageView* popLabelBackImg = (UIImageView*)[self.view viewWithTag:POPVIEW_IMAGEVIEW_TAG];
        
        UILabel* label = (UILabel*)[self.view viewWithTag:POPVIEW_LABEL_TAG];
        popLabelBackImg.alpha = 1.0;
        label.alpha = 1.0;
        label.text = title;
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:36];
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationDuration: 1.0];
        label.alpha = 0.0;
        popLabelBackImg.alpha = 0.0;
        [UIView commitAnimations];  
        //控制跳转位置的返回当前选择的索引在 数组里的位置 如果当前选择的索引在数组里不存在，则返回值为上次的值
        charIndex = (unsigned)CFArrayBSearchValues((CFArrayRef) keys,
                                                             CFRangeMake(0, CFArrayGetCount((CFArrayRef)keys)),
                                                             (CFStringRef)title,
                                                             (CFComparatorFunction)CFStringCompare,
                                                             NULL);
    }
    return charIndex;
 
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG]) {
        return [self.keys count];
    }
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    if(tableView == [self.view viewWithTag:TABLEVIEW_TAG])
    {
        NSString *key = [keys objectAtIndex:section];
        NSArray *contact = [composeMessageView.allContactDic objectForKey:key];
        return [contact count];
    }
    return [self.filteredListContent count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"Cell";
    
    selectTableCell *cell = (selectTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[selectTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
		cell.textLabel.font = [cell.textLabel.font fontWithSize:17];
    }
	
	cell.accessoryType = UITableViewCellAccessoryNone;
	
   
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG])
	{
        NSString *key = [keys objectAtIndex:indexPath.section];
        NSArray *contactlist = [composeMessageView.allContactDic objectForKey:key];
       
    }
	
	
    [cell setContactImage:[UIImage imageNamed:@"contacts_icon.png"] contactName:@"fda" checked:YES];
	
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	ContactInfo* infoItem = nil;
	
    selectTableCell *cell = (selectTableCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (tableView == [self.view viewWithTag:TABLEVIEW_TAG])
	{
        NSString *key = [keys objectAtIndex:indexPath.section];
        NSArray *contactlist = [composeMessageView.allContactDic objectForKey:key];
        infoItem = [contactlist objectAtIndex:indexPath.row];
    }
	else
	{
        infoItem = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    
    infoItem.checked = !infoItem.checked;
    [cell setChecked:infoItem.checked];

    if (infoItem.checked) {
        if (![composeMessageView.receptionArray containsObject:infoItem]) {
            [composeMessageView.receptionArray addObject:infoItem];
        }        
    }
    else{
        if ([composeMessageView.receptionArray containsObject:infoItem]) {
            [composeMessageView.receptionArray removeObject:infoItem];
        }
    }
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
	/*
	 Update the filtered array based on the search text and scope.
	 */
	
	[filteredListContent removeAllObjects]; // First clear the filtered array.
	
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

#pragma mark -
#pragma mark UISearchBarDelegate Delegate Methods

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar{
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{    
    [searchBar setShowsCancelButton:YES animated:YES];    
    for(UIView *subView in searchBar.subviews){        
        if([subView isKindOfClass:UIButton.class]){            
            [(UIButton*)subView setTitle:@"列表" forState:UIControlStateNormal];            
        }        
    }
    return YES;
}
@end
